<template>
  <div class="view-fill">
    <div
      v-if="
        !exportInfo.visible &&
        !applicationOrderInfo.visible &&
        !downShelfTaskInfo.visible &&
        !purchOrderIndfo.visible &&
        !useApplicationModifyInfo.visible
      "
      class="app-container-flex"
    >
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <el-button
            :plain="true"
            @click="replenishStock"
            v-if="$permission('useAudit:replenishStock')"
            >补充库存</el-button
          >

          <el-button v-if="canAudit" :plain="true" @click="audit"
            >批准</el-button
          >
          <el-button
            v-if="canReject && $permission('useAudit:reject')"
            :plain="true"
            @click="reject"
            >驳回</el-button
          >
          <el-button
            v-if="canExport && $permission('useAudit:export')"
            :plain="true"
            @click="toEextort"
            >生成出库单</el-button
          >
          <!-- <el-button
            v-if="
              canExport &&
              $permission('useAudit:downShelfTask') &&
              infoList.data.isCargoSpaceManage == 1
            "
            :plain="true"
            @click="downShelfTask"
            >生成wms出库单</el-button
          > -->
          <el-button
            v-if="canPurch && $permission('useAudit:auditPurch')"
            @click="auditPurch"
            >转为采购单</el-button
          >
          <el-button
            v-if="canPurch && $permission('useAudit:auditApplication')"
            @click="auditApplication"
            >转为申购单</el-button
          >
          <el-button
            v-if="canStop && $permission('useAudit:stop')"
            @click="stopRow"
            >中止</el-button
          >
          <el-button
            v-if="$permission('useAudit:exportExcel')"
            :plain="true"
            @click="exportExcel"
            >导出excel</el-button
          >
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="canComplete"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <BasicInformation
              :info="infoList"
              :label-width="infoList.labelWidth"
            ></BasicInformation>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title div-flex">
            <Tooltip :text="$t('detailInfo')" />
            <ModelTips
              :items="modelTipsInfo.items"
              :title="modelTipsInfo.title"
              :brackets="true"
            />
          </div>
          <div class="model-panel-body">
            <PageFilter
              v-model:query="filterInfo.query"
              :filter-list="filterInfo.list"
            ></PageFilter>
            <div class="flex_full_item">
              <div class="flex_full_item">
                <!-- 表格 -->
                <PageTable
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :summary="true"
                  :check-box="false"
                  :tab-index="true"
                  :summary-field-list="tableInfo.summaryFieldList"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :row-class-name="tableRowClassName"
                  :isDynamic="true"
                >
                  <template v-slot:col-purch="scope">
                    <p>
                      {{
                        (scope.row.applicationQty
                          ? scope.row.applicationQty
                          : 0) + (scope.row.purchQty ? scope.row.purchQty : 0)
                      }}
                    </p>
                    <p>{{ scope.row.cancelQty || 0 }}</p>
                  </template>
                </PageTable>
              </div>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <export
      v-if="exportInfo.visible"
      :id="exportInfo.id"
      v-model:visible="exportInfo.visible"
      :title="exportInfo.title"
      @returnModify="getCustomize"
    />
    <purch-order
      v-if="purchOrderIndfo.visible"
      v-model:visible="purchOrderIndfo.visible"
      :orderId="purchOrderIndfo.orderId"
      :useOrderNo="purchOrderIndfo.useOrderNo"
      @returnModify="getCustomize"
    />
    <application-order
      v-if="applicationOrderInfo.visible"
      v-model:visible="applicationOrderInfo.visible"
      :orderId="applicationOrderInfo.orderId"
      :useOrderNo="applicationOrderInfo.useOrderNo"
      @returnModify="getCustomize"
    />
    <DownShelfTask
      v-if="downShelfTaskInfo.visible"
      v-model:visible="downShelfTaskInfo.visible"
      :title="downShelfTaskInfo.title"
      :id="downShelfTaskInfo.id"
      @returnModify="getCustomize"
    />
    <use-application-modify
      v-if="useApplicationModifyInfo.visible"
      v-model:visible="useApplicationModifyInfo.visible"
      :title="useApplicationModifyInfo.title"
      @returnModify="getCustomize"
      :id="useApplicationModifyInfo.id"
      :auditData="useApplicationModifyInfo.auditData"
    />
  </div>
</template>

<script setup name="useAuditDetails">
import {
  detailUseApplication,
  rejectUseApplication,
  getUseApplicationDetailCustomizeList,
  getAuditPrint,
  exportUseRatify,
  auditUseApplication,
  stopUseApplication,
  validateDepotHighLevel,
  validateDownShelf,
  useApplicationReplenishStock,
} from '@/api/use.js'

import { orderAffairAll } from '@/api/affair'
import Export from './export'
import PurchOrder from './purch'
import DownShelfTask from './downShelfTask'
import ApplicationOrder from './application'
import { getCustomizeSetting } from '@/api/customize'
import { fatchTemplateByCode } from '@/api/base'
import { getDepotPage } from '@/api/core.js'
import UseApplicationModify from '../application/modify'
import { doPrint } from '@/utils/exportUtil.js'
import { selectByCodeAndDept } from '@/api/report.js'
import { updatePrintCount } from '@/api/mapping'

import utils from '@/common/js/utils'

const { proxy } = getCurrentInstance()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  id: {
    type: [Number, String],
  },
})
const modelTipsInfo = ref({
  title: '高水位预警',
  items: [
    {
      label: '超过',
      style: { width: '10px', height: '10px', background: '#f7c1c1' },
    },
  ],
})
const title = ref('领用单详情')
const infoList = ref({
  data: {},
  fieldList: [
    { label: '领用申请单号', value: 'orderNo', type: 'text' },
    { label: '领用人', value: 'createUserName', type: 'text' },
    { label: '状态', value: 'statusValue', type: 'text' },
    { label: '领用部门', value: 'deptName', type: 'text' },
    { label: '领出部门', value: 'exportDeptName', type: 'text' },
    { label: '领出仓库', value: 'exportDepotName', type: 'text' },
    { label: '领入仓库', value: 'depotName', type: 'text' },
    { label: '领用日期', value: 'applicationTime', type: 'text' },
    { label: '创建人', value: 'createUserName', type: 'text' },
    { label: '创建时间', value: 'createTime', type: 'text' },
    { label: '更新人', value: 'updateUserName', type: 'text' },
    { label: '更新时间', value: 'updateTime', type: 'text' },
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'text',
    },
    { label: '备注', value: 'remark', type: 'text' },
  ],
  labelWidth: '130px',
})
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
})
const affairTableInfo = ref({
  query: {
    orderType: 19,
    orderId: props.id,
    sort: 'operate_time desc',
  },
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id,
      },
      acquisitionReplaceConsume: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {},
    customizeUserVO: {},
  },
  list: [
    {
      label: '类型',
      value: 'acquisitionReplaceConsume',
      type: 'select-model',
      checkDefault: true,
      clearable: false,
      code: 'acquisition_replace_consume',
      event: changeType,
    },
  ],
})
const exportInfo = ref({
  visible: false,
  title: '领用单出库',
  id: '',
})
const downShelfTaskInfo = ref({
  visible: false,
  title: '领用单拣货',
  id: '',
})
const purchOrderIndfo = ref({
  visible: false,
  orderId: '',
})
const applicationOrderInfo = ref({
  visible: false,
  orderId: '',
})
const useApplicationModifyInfo = ref({
  visible: false,
  auditData: {},
  title: '补充库存',
  id: '',
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    proxy.$emit('update:visible', val) // 更新父组件visible
  },
})
const canComplete = computed(() => {
  return infoList.value.data.status !== 2 && proxy.$permission('useAudit:print')
})
const canPurch = computed(() => {
  return infoList.value.data.status === 4 || infoList.value.data.status === 7
})
const canStop = computed(() => {
  return infoList.value.data.status === 4 || infoList.value.data.status === 7
})
const canAudit = computed(() => {
  return infoList.value.data.status === 2 && proxy.$permission('useAudit:audit')
})
const canReject = computed(() => {
  return (
    (infoList.value.data.status === 2 ||
      (infoList.value.data.status == 4 &&
        infoList.value.data.isCargoSpaceManage != 1)) &&
    proxy.$permission('useAudit:reject')
  )
})
const canExport = computed(() => {
  return infoList.value.data.status === 4 || infoList.value.data.status === 7
})
watch(
  () => props.visible,
  (val) => {
    showDialog.value = val
  },
  { immediate: true }
)

function tableRowClassName({ row }) {
  if (row.hasOwnProperty('depotStockHighQty')) {
    let qty = proxy.$fn.accDiv(
      proxy.$fn.accAdd(row.calcQty || 0, row.depotStockCalcQty),
      row.unitConvertCoefficient
    )
    if (qty > row.depotStockHighQty) {
      return 'warning-row'
    } else {
      return ''
    }
  }
  return ''
}
function returnBack() {
  proxy.$emit('returnBack', false)
}
function getList() {
  getUseApplicationDetailCustomizeList(filterInfo.value.query).then((resp) => {
    if (resp && resp.success) {
      tableInfo.value.data = resp.data
    }
  })
}
//补充库存
function replenishStock() {
  //跳转领用申请新增页

  //自动带出可领仓库第一个
  let exportDepotQuery = {}
  exportDepotQuery.subDepotId = infoList.value.data.exportDepotId
  exportDepotQuery.searchType = 'depot'
  exportDepotQuery.status = '1'
  exportDepotQuery.useTypeId = '1'
  exportDepotQuery.sort = 'create_time desc'
  useApplicationModifyInfo.value.visible = true
        useApplicationModifyInfo.value.auditData = infoList.value.data
        useApplicationModifyInfo.value.auditData.details = tableInfo.value.data
  // getDepotPage(exportDepotQuery).then((res) => {
  //   if (res.success && res.data) {
  //     if (res.data.length == 0) {
  //       proxy.$message.error('当前仓库没有可领仓库')
  //     } else {
  //       useApplicationModifyInfo.value.visible = true
  //       useApplicationModifyInfo.value.auditData = infoList.value.data
  //       useApplicationModifyInfo.value.auditData.details = tableInfo.value.data
  //     }
  //   }
  // })
}

function audit() {
  const ids = [infoList.value.data.id]
  validateDepotHighLevel(ids).then((res) => {
    if (res && res.success) {
      auditUseApplication(ids).then((resp) => {
        if (resp && resp.success) {
          getMain()
        }
      })
    }
  })
}
function changeType(val) {
  if (val == '1') {
    filterInfo.value.query.queryMap.acquisitionReplaceConsume.value = 1
  } else if (val == '0') {
    filterInfo.value.query.queryMap.acquisitionReplaceConsume.value = null
  }
  getList()
}
//驳回，其实和撤回是同样的效果
function reject() {
  proxy
    .$prompt('驳回理由', '领用审核', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /^[\S]+/,
      inputErrorMessage: '请输入驳回理由',
    })
    .then(({ value }) => {
      let param = {}
      param.ids = [infoList.value.data.id]
      param.remark = value
      rejectUseApplication(param).then((resp) => {
        if (resp && resp.success) {
          getMain()
        }
      })
    })
    .catch(() => {})
}

function authAudit(data, msg) {
  console.log(msg)
  const flag =
    (data.length && data.every((item) => item.calcQty <= item.convertCount)) ||
    false
  if (flag) {
    proxy.$message({
      message: msg,
      type: 'warning',
      duration: 3500,
    })
  }
  return flag
}
function auditPurch() {
  //转采购
  const result = authAudit(tableInfo.value.data, '该领用单已转过采购单！')
  if (result) return
  purchOrderIndfo.value.visible = true
  purchOrderIndfo.value.orderId = props.id
  purchOrderIndfo.value.useOrderNo = infoList.value.data.orderNo
}
function auditApplication() {
  //转申购
  const result = authAudit(tableInfo.value.data, '该领用单已转过申购单！')
  if (result) return
  applicationOrderInfo.value.visible = true
  applicationOrderInfo.value.orderId = props.id
  applicationOrderInfo.value.useOrderNo = infoList.value.data.orderNo
}
function stopRow() {
  //中止
  proxy
    .$confirm('中止后将改变数据,是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      stopUseApplication([props.id]).then((resp) => {
        if (resp && resp.success) {
          getList()
        }
      })
    })
}
//出库
function toEextort() {
  exportInfo.value.visible = true
  exportInfo.value.id = props.id
}
function downShelfTask() {
  //校验能否拣货
  validateDownShelf(props.id).then((resp) => {
    if (resp && resp.success) {
      downShelfTaskInfo.value.visible = true
      downShelfTaskInfo.value.id = props.id
    }
  })
}
//导出excel
function exportExcel() {
  exportUseRatify(filterInfo.value.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}

const templateArr = ref([])
const popoverVisible = ref(false)
//打印
function print() {
  selectByCodeAndDept({
    tempCode: 'useAuditDetail',
    deptId: infoList.value.data.deptId,
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            applicationId: infoList.value.data.id,
            orderId: infoList.value.data.id,
            orderNo: infoList.value.data.orderNo,
          },
          callback: printCallback,
          printCount: true,
          data: {},
        })
      }
    }
  })
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      applicationId: infoList.value.data.id,
      orderId: infoList.value.data.id,
      orderNo: infoList.value.data.orderNo,
    },
    callback: printCallback,
    printCount: true,
    data: {},
  })
  popoverVisible.value = false
}
function printCallback() {
  try {
    // 打印成功增加打印次数
    updatePrintCount({
      orderNo: infoList.value.data.orderNo,
      tempCode: 'useAuditDetail',
      orderId: props.id,
      orderType: 19,
    })
  } catch (error) {}
}
function getMain() {
  detailUseApplication(props.id).then((resp) => {
    if (resp && resp.success) {
      infoList.value.data = resp.data
      getList()
    }
  })
}
function getCustomize() {
  let param = {
    tableKey:
      'useApplicationOrderDetail-com.slip.spd.entity.vo.use.UseApplicationOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = res.data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      getMain()
    }
  })
}

let obj = {
  orderNo: {
    label: '单号',
    value: 'orderNo',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  storeStockQty: {
    label: '领入仓库可用数量',
    value: 'storeStockQty',
    hidden: true,
    type: 'column',
    formatter: utils.qtyFormatter,
    componentType: 'number',
  },
  exportStockQty: {
    label: '领出仓库可用数量',
    value: 'exportStockQty',
    hidden: true,
    type: 'column',
    formatter: utils.qtyFormatter,
    componentType: 'number',
  },
  price: {
    label: '单价',
    value: 'price',
    minWidth: '150px',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('useAudit:price'),
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('useAudit:price'),
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    componentType: 'price',
    permission: !proxy.$permission('useAudit:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
    show: false,
  },
  preExportQty: {
    label: '预出库数量',
    value: 'preExportQty',
    type: 'column',
    show: false,
    hidden: true,
  },
  exportQty: {
    label: '出库数量',
    value: 'exportQty',
    type: 'column',
    show: false,
    hidden: true,
  },
  storeQty: {
    label: '入库数量',
    value: 'storeQty',
    type: 'column',
    show: false,
    hidden: true,
  },
  availableQty: {
    label: '可出库数量',
    value: 'availableQty',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()
</script>

<style scoped></style>
